package product;

import models.constants.DeletedStatus;
import play.db.jpa.Model;
import product.merchant.ProductSpecMerchant;
import util.common.ConvertUtil;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 产品图片
 * Created by buhaoba on 16/6/14.
 */
@Entity
@Table(name = "product_spec_images")
public class ProductSpecImage extends Model {


    /**
     * 产品详细信息
     */
    @JoinColumn(name = "product_spec_id")
    @ManyToOne
    public ProductSpec productSpec;

    /**
     * 产品图片
     */
    @Column(name = "img_path")
    public String imgPath;

    /**
     * 创建时间
     */
    @Column(name = "created_at")
    public Date createdAt;

    /**
     * 逻辑删除,0:未删除，1:已删除
     */
    @Enumerated(EnumType.ORDINAL)
    public DeletedStatus deleted;

    /**
     * 根据产品详细ID查询产品详细图片
     */
    public static List<ProductSpecImage> loadByProductSpecId(long productSpecId) {
        return ProductSpecImage.find("productSpec.id = ? and deleted = ?", productSpecId, DeletedStatus.UN_DELETED).fetch();
    }

    /**
     * 根据产品详细ID查询产品详细图片
     */
    public static ProductSpecImage loadFirstByProductSpecId(long productSpecId) {
        return ProductSpecImage.find("productSpec.id = ? and deleted = ?", productSpecId, DeletedStatus.UN_DELETED).first();
    }

    /**
     *同一商户 同一产品 不同规格的 规格图片
     * @param productSpecMerchant 商户商品
     * @return
     */
    public static List<ProductSpecImage> loadByProductSpecMerchant(ProductSpecMerchant productSpecMerchant){
        List<ProductSpecImage> resultList = new ArrayList<>();
        List<ProductSpecMerchant> specMerchantList = ProductSpecMerchant.loadByProductSpecMerchant(productSpecMerchant);
        String str = "";
        for(ProductSpecMerchant specMerchant : specMerchantList){
            str +=","+ ConvertUtil.toString(specMerchant.productSpec.id);
        }
        if(!str.equals("")){
            str = str.substring(1);
            resultList = ProductSpecImage.find("productSpec.id in (" + str + ") and deleted = ? and productSpec.deleted = ?", DeletedStatus.UN_DELETED, DeletedStatus.UN_DELETED).fetch();
        }
        return resultList;
    }
    /**
     * 删除产品图片
     *
     * @param productSpecId
     */
    public static void delProductImg(long productSpecId) {
        ProductSpecImage productSpecImage = ProductSpecImage.findById(productSpecId);
        productSpecImage.deleted = DeletedStatus.DELETED;
        productSpecImage.save();
    }

    /**
     * 加载产品规格第一张图片
     * @param productSpecId
     * @return
     */
    public static ProductSpecImage loadFirstProductSpecImage(long productSpecId) {
        return ProductSpecImage.find("productSpec.id=? and deleted=? order by id", productSpecId, DeletedStatus.UN_DELETED).first();
    }



}
